//
//  JYOAuthViewController.swift
//  WeiBoDemo
//
//  Created by 万佳阳 on 16/8/3.
//  Copyright © 2016年 JYWan. All rights reserved.
//

import UIKit
import SVProgressHUD

class JYOAuthViewController: UIViewController {

    // MARK:- 系统回调函数
    override func loadView() {
        view = UIWebView()
        view.backgroundColor = UIColor.whiteColor()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //加载导航栏内容
        setupNavigationBar()
        
        //加载网页
        loadPage()
        
    }

}

// MARK:- 设置UI界面
extension JYOAuthViewController {
    ///加载导航栏内容
    private func setupNavigationBar() {
        title = "登录页面"
        
        //设置左边item
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: #selector(JYOAuthViewController.closeItemClick))
        
        //设置右边item
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "填充", style: .Plain, target: self, action: #selector(JYOAuthViewController.fillItemClick))
    }
    
    ///加载网页
    private func loadPage() {
        //获取登录界面的URLString
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(app_key)&redirect_uri=\(redirect_uri)"
        
        //获取URL
        guard let url = NSURL(string: urlString) else {
            return
        }
        
        //创建URLRequest对象
        let request = NSURLRequest(URL: url)
        
        //加载URLRequest
        (view as! UIWebView).loadRequest(request)
        
        //设置代理
        (view as! UIWebView).delegate = self
    }
}

// MARK:- 事件监听
extension JYOAuthViewController {
    @objc private func closeItemClick() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func fillItemClick() {
        //书写JS代码
        let JSCode = "document.getElementById('userId').value='15574574038';document.getElementById('passwd').value='yang1314aini';"
        //执行JS
        (view as! UIWebView).stringByEvaluatingJavaScriptFromString(JSCode)
    }
}

// MARK:- <UIWebViewDelegate>
extension JYOAuthViewController : UIWebViewDelegate {
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //获取加载网页的URL
        guard let url = request.URL else {
            return true
        }
        
        //获取URL中底字符串
        let urlString = url.absoluteString
        
        //判断字符串中是否包含code
        guard urlString.containsString("code=") else {
            return true
        }
        
        //截取code
        let code = urlString.componentsSeparatedByString("code=").last!
        
        //请求accessToken
        loadAccessToken(code)
        
        return false
    }
}

// MARK:- 请求数据
extension JYOAuthViewController {
    ///请求accessToken
    private func loadAccessToken(code : String) {
        NetworkTools.shareInstance.loadAccessToken(code) { (result, error) in
            //错误校验
            if error != nil {
                print(error)
                return
            }
            
            //拿到结果
            guard let accountDict = result else {
                print("没有获取到授权后到数据")
                return
            }
            
            //字典转模型
            let userAccount = JYUserAccount(dict: accountDict)
            
            //请求用户信息
            self.loadUserInfo(userAccount)
        }
    }
    
    ///请求用户信息
    private func loadUserInfo(userAccount : JYUserAccount) {
        //获取access_token
        guard let access_token = userAccount.access_token else {
            return
        }
        
        //获取uid
        guard let uid = userAccount.uid else {
            return
        }
        
        //发送请求
        NetworkTools.shareInstance.loadUserInfo(access_token, uid: uid) { (result, error) in
            //错误校验
            if error != nil {
                print(error)
                return
            }
            
            //拿到用户信息结果
            guard let userInfoDict = result else {
                return
            }
            
            //从字典中取出昵称和头像URL
            userAccount.name = userInfoDict["name"] as? String
            userAccount.avatar_large = userInfoDict["avatar_large"] as? String
            
            //保存用户信息
            NSKeyedArchiver.archiveRootObject(userAccount, toFile: JYUserAccountViewModel.shareInstance.accountpath)
            
            //将userAccount设置到单例对象中
            JYUserAccountViewModel.shareInstance.userAccount = userAccount
            
            //退出当前控制器
            self.dismissViewControllerAnimated(false, completion: {
                UIApplication.sharedApplication().keyWindow?.rootViewController = JYWelcomeViewController()
            })
        }
    }
}